package com.shop.controller;

import com.alibaba.fastjson.JSON;
import com.shop.entity.Order;
import com.shop.entity.ShowPageT;
import com.shop.entity.TOrder;
import com.shop.entity.User;
import com.shop.servlet.OrderServlet;
import com.shop.servlet.impl.OrderServletImpl;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * com.shop.controller文档说明
 *
 * @author Angluzha
 * @version 2022/9/17
 */
@WebServlet("/order/*")
public class OrderController extends BaseController{
    {
        servlet = new OrderServletImpl();
    }
    public String selectAll(){
        ShowPageT<TOrder> pageT = (ShowPageT<TOrder>) req.getAttribute("pageT");
        page(pageT,"/goods/selectAll");
        return forward("/back/order/orderlist.jsp");
    }
    public String checkTOrder(){
        ShowPageT<TOrder> pageT = (ShowPageT<TOrder>) req.getAttribute("pageT");
        String page = req.getParameter("page");
        if(pageT==null){
            pageT = new ShowPageT<>();
        }
        if(page==null||"".equals(page)){
            page = "1";
        }
        pageT.setPage(Integer.parseInt(page));
        pageT = ((OrderServletImpl)servlet).checkTorder(pageT);;
        pageT.setUri("/goods/checkTOrder");
        req.setAttribute("pageT",pageT);

        return forward("/back/order/orderlist.jsp");
    }
    public String delete(Order order){
        ((OrderServletImpl)servlet).removeTOrderById(order.getId());
        return redirect("/goods/checkTOrder");
    }
    public String save(Order order){
        servlet.insert(order);
        return forward("/back/order/orderlist.jsp");
    }
    public String create(){
        try {
            String line = req.getReader().readLine();
            Order order = JSON.parseObject(line, Order.class);
            HttpSession session = req.getSession();

            List<Order> orders = (List<Order>) session.getAttribute("orders");
            order.setUser(((User) session.getAttribute("user")).getId());
            order.setSpend((BigDecimal) session.getAttribute("sum"));
            if (((OrderServlet)servlet).createOrder(order,orders)) {
                session.removeAttribute("orders");
                session.removeAttribute("sum");
                return writeWeb("ok");
            }else{
                return writeWeb("no");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return writeWeb("no");
    }
}
